package model

import (
	"time"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/enum/stateenum"
)

type AdminDepartment struct {
	Id             uint64             `gorm:"primary_key;autoIncrement;column:id" json:"id,omitempty" form:"id"`
	Pid            uint64             `gorm:"column:pid;not null;default:0" json:"pid"`
	Pids           Uint64SliceJson    `gorm:"type:json;column:pids;comment:所有的父级id" json:"pids" form:"pids"`
	Type           uint8              `gorm:"column:type;not null;default:0" json:"type"`
	Name           string             `gorm:"column:name;type:varchar(128);not null" json:"name"`
	FullName       string             `gorm:"type:varchar(500);not null;default:'';column:full_name;comment:完整名称，父级名称拼接" json:"full_name" form:"full_name"`
	Code           string             `gorm:"column:code;type:varchar(64);not null;default:''" json:"code"`
	Intro          string             `gorm:"column:intro;type:varchar(255);not null;default:''" json:"intro"`
	Sort           int                `gorm:"column:sort;not null;default:0" json:"sort"`
	CreatedAt      *time.Time         `gorm:"column:created_at" json:"created_at,omitempty" form:"created_at"`
	UpdatedAt      *time.Time         `gorm:"column:updated_at" json:"updated_at,omitempty" form:"updated_at"`
	State          uint8              `gorm:"column:state" json:"state" form:"state"`
	SubDepartments []*AdminDepartment `gorm:"-" json:"sub_departments"` // 子部门

	allPostions []*AdminPostion // 部门岗位
}

// 初始化子部门
func (m *AdminDepartment) InitSubDepartments(departments []*AdminDepartment) {
	if m.SubDepartments == nil {
		m.SubDepartments = []*AdminDepartment{}
	}
	for _, department := range departments {
		if department.Pid == m.Id {
			m.SubDepartments = append(m.SubDepartments, department)
		}
	}
}

// 获取部门下属岗位数据
func (m *AdminDepartment) GetAllPostions() (postions []*AdminPostion, err error) {
	if m.allPostions == nil {
		var positions []*AdminPostion
		tablePrefix := global.Config.Database.TablePrefix
		err = global.MySQL.Table(tablePrefix+"admin_department_postion as dp").
			Joins("JOIN "+tablePrefix+"admin_postion as p on dp.postion_id = p.id").
			Select("p.*, dp.type").
			Where("dp.department_id = ?", m.Id).
			Order("p.sort asc").
			Find(&positions).Error
		if err == nil {
			m.allPostions = positions
		}
	}
	postions = m.allPostions
	return
}

// 获取部门下属状态正常的岗位数据
func (m *AdminDepartment) GetNormalPostions() (postions []*AdminPostion, err error) {
	allPostions, err := m.GetAllPostions()
	if err != nil {
		return
	}
	postions = make([]*AdminPostion, 0, len(allPostions))
	for _, v := range allPostions {
		if v.State == stateenum.NORMAL {
			postions = append(postions, v)
		}
	}
	return
}
